package com.traffic.between.service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.traffic.between.config.BetweenProperties;
import com.traffic.between.util.Base64;
import com.traffic.between.util.HttpClientUtils;


public class ZhejiangServiceImpl {
	private static Logger LOG = Logger.getLogger(ZhejiangServiceImpl.class);
	public static ZhejiangServiceImpl service = new ZhejiangServiceImpl();

	private static String HOST_PATH = BetweenProperties.ZHEJIANG_URL;
	private static String ZHEJIANG_APPKEY = BetweenProperties.ZHEJIANG_APPKEY;
	private static String ZHEJIANG_APPSECRET = BetweenProperties.ZHEJIANG_APPSECRET;

	public String order(String transNo, String pkgNo, String phoneNo, String backUrl) {
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("action", "orderPkg");
		params.put("appKey", ZHEJIANG_APPKEY);
		params.put("pkgNo", pkgNo);
		params.put("phoneNo", phoneNo);

		params.put("transNo", transNo);
		String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		params.put("timeStamp",timeStamp);
		params.put("backUrl",Base64.encode(backUrl));

		String result = "";
		String signParam = new StringBuilder().append(ZHEJIANG_APPSECRET).append(dataSort(params)).append(ZHEJIANG_APPSECRET).toString();
		String sign = SHA1(signParam);
		
		List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
		pairList.add(new BasicNameValuePair("action","orderPkg"));
		pairList.add(new BasicNameValuePair("appKey",ZHEJIANG_APPKEY));
		pairList.add(new BasicNameValuePair("pkgNo", pkgNo));
		pairList.add(new BasicNameValuePair("phoneNo", phoneNo));
		pairList.add(new BasicNameValuePair("transNo", transNo));
		pairList.add(new BasicNameValuePair("timeStamp",timeStamp));
		pairList.add(new BasicNameValuePair("backUrl",Base64.encode(backUrl)));
		pairList.add(new BasicNameValuePair("sign",sign.toUpperCase()));
		
		LOG.info("between- 浙江订购请求时的参数: "+pairList);
		try {
			HttpPost httpPost = new HttpPost(HOST_PATH);
			CloseableHttpClient client = HttpClients.createDefault();
		    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(30000).build();//设置请求和传输超时时间
		    httpPost.setConfig(requestConfig);
			httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));
			HttpResponse response = client.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			LOG.info("between- 浙江订购请求时的响应statusCode: " + statusCode+",该订单号为："+transNo);
			
			result = EntityUtils.toString(response.getEntity(), "utf-8");
			LOG.info("between- 浙江订购请求时的响应数据是: " + result + ",该订单号为：" + transNo);
			
		} catch (Exception e) {
			LOG.info("between- 浙江订购请求时请求时异常: " + e +",该订单号为：" + transNo);
			Map<String,Object> map = new HashMap<String, Object>();
			if (e.getMessage().contains("Read timed out")) {
				map.put("respCode","0001");
				map.put("orderId","");
			}else {
				map.put("respCode","-1111");
				map.put("orderId","");
			}
			
			result = new Gson().toJson(map);
		}
		return result;
       
	}

	public String orderStatus(String orderId) {
		LOG.info(new StringBuilder().append("zhejiang orderStatus request: orderId[").append(orderId).append("]")
				.toString());

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("action", "queryOrder");
		params.put("appKey", ZHEJIANG_APPKEY);
		params.put("orderId", orderId);
		params.put("timeStamp", new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));

		String signParam = new StringBuilder().append(ZHEJIANG_APPSECRET).append(dataSort(params))
				.append(ZHEJIANG_APPSECRET).toString();
		String sign = SHA1(signParam);
		params.put("sign", sign.toUpperCase());
		String result = new HttpClientUtils().doGet(params, "utf-8", HOST_PATH);
		LOG.info(new StringBuilder().append("zhejiang orderStatus response: ").append(result).append(",该订单号为："+orderId).toString());
		return result;
	}

	public String dataSort(Map<String, Object> params) {
		StringBuilder sb = new StringBuilder();
		Object[] keys = params.keySet().toArray();
		Arrays.sort(keys);
		for (Object key : keys) {
			sb.append(key).append(params.get(key));
		}
		return sb.toString();
	}

	public String SHA1(String decript) {
		try {
			MessageDigest digest = MessageDigest.getInstance("SHA-1");

			digest.update(decript.getBytes());
			byte[] messageDigest = digest.digest();

			StringBuffer hexString = new StringBuffer();

			for (int i = 0; i < messageDigest.length; ++i) {
				String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
				if (shaHex.length() < 2) {
					hexString.append(0);
				}
				hexString.append(shaHex);
			}
			return hexString.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return "";
	}
}